open BUFF,"<merge_expr_sortedage" or die "no file exists merge_expr\n";
open BUFF1,"<combined_GBM_normal_final_hthoLT15.tped" or die "no file exists combined_GBM_normal_final_maf05.tped\n";
open(WRBUFF,">merge_expr_sortedage_commonsamples");
open(WRBUFF1,">combined_GBM_normal_final_hthoLT15_out.tped");
#read the first line in  expr file for sample names
$line = <BUFF>;
chomp($line);
$line =~ s/^\t+//g;
#print $line."\n";
#create sample array expr
@gene_samples = split(/\t/,$line);
print "@gene_samples\n";
for($i=0;$i<@gene_samples;$i++)
{
	$hsh{$gene_samples[$i]} = 1;
}
#read the first line in tped file for sample names
$line = <BUFF1>;
chomp($line);
$line =~ s/^\s+//g;
#create sample array
@geno_samples = split(" ",$line);
print "@geno_samples\n";
#for loop for creating hash name with serial numbers
$num =0;
for($i=0;$i<@geno_samples;$i++)
{
	if(exists($hsh{$geno_samples[$i]}))
	{
		#print "sucess\n";
#geno_array storing the samples which are included starting from 0
		$geno_array[$num] = $geno_samples[$i];
#creating the hash with positions asigned to samples
		$hash{$geno_samples[$i]} = $num;
#geno_samples creating vector with including samples as increments number and other as -1 [starting from 0)
#		print $num."\n";
		$geno_samples[$i] = $num;
		$num++;
	}
	else
	{
		$geno_samples[$i] = -1;
	}
}
$line = join(" ",@geno_array);
print WRBUFF1 "$line\n";
#print "@geno_array\n";
#print "@geno_samples\n";
#create array initial elemen to gene
#loop through the expr samples and asign the tped sample serial number to expr samples
for($i=0;$i<@gene_samples;$i++)
{
#creating hash1 to eliminate duplicates and asign -1 position for the duplicate
	if(exists($hash{$gene_samples[$i]}) && (!exists($hash1{$gene_samples[$i]})))
	{
		$hash1{$gene_samples[$i]} = $hash{$gene_samples[$i]};
		$gene_array[$hash{$gene_samples[$i]}] = $gene_samples[$i]; 
	}
	else
	{
		$hash1{$gene_samples[$i]} = -1;
	}
	$gene_samples[$i] = $hash1{$gene_samples[$i]};
}
$line = join("\t",@gene_array);
print WRBUFF "$line\n";
#print "@gene_array\n";
#print "@gene_samples\n";

#$line = <BUFF>;
while($line = <BUFF>)
{
	chomp($line);
	@array = split(/\t/,$line);
	$array1[0] = $array[0];
	for($i=1;$i<@array;$i++)
	{
		if($gene_samples[$i-1] != -1)
		{
			$array1[$gene_samples[$i-1]+1] = $array[$i]; 			
		}
	}
	$line =join("\t",@array1);
	print WRBUFF "$line\n";
}
#$line = <BUFF1>;
while($line = <BUFF1>)
{
        chomp($line);
        @array2 = split(/ /,$line);
        $array3[0] = $array2[0];
	$array3[1] = $array2[1];
	$array3[2] = $array2[2];	
	$array3[3] = $array2[3];
	#$array3[4] = $array2[4];
        #$array3[5] = $array2[5];
        #$array3[6] = $array2[6];

        #for($i=7;$i<@array2;$i++)
	for($i=4;$i<@array2;$i++)
        {
                if($geno_samples[$i-4] != -1)
                {
                        $array3[$geno_samples[$i-4]+4] = $array2[$i];
                }
        }
        $line =join(" ",@array3);
	print WRBUFF1 "$line\n";
}



